<?php

namespace App\Service\Collect;

use App\Service\BaiduNlp;
use Illuminate\Support\Facades\Cache;
use QL\QueryList;

class Dispatch extends Base
{
    // 从财通社采集快讯

    // 初始化
    protected function init()
    {
        parent::init();
    }


    // 保存到数据表
    public function saveApiDataToDb($_item, $key, $is_file = false)
    {
        $_id    = $_item['id'];
        $_brief = $_item['brief'];
        $_date  = $_item['create_time'];   // 2020-01-17 18:41
        $_ctime = strtotime($_date); // 时间
        $_href  = 'https://www.caitongnews.com/live/'.$_id.'.html';
        if(mb_substr($_brief, 0, 1) == "【"){
            $pos    = mb_strpos($_brief, "】");
            $_title = mb_substr($_brief, 1, $pos - 1);
            $_desc  = mb_substr($_brief, $pos + 1);
        } else{
            $_title = '';
            $_desc  = $_brief;
        }


        // 采集地址
        $_href = $this->realHref($_href);
        // 判断链接是否已经采集
        if($is_file){
            $info = $this->isGatherFile($_href);
        } else{
            $info = $this->isGather($_href);
        }
        if($info){
            if(empty($info['sentiment'])){
                $sentiment = $this->baiduNlp($info['text'] ?: $info['description']);
                if($sentiment){
                    if($is_file){
                        $info['sentiment'] = $sentiment;
                        $this->updateFile($_href, $info);
                    } else{
                        $this->updateArticle($info['id'], ['sentiment' => $sentiment]);
                    }
                }
            }

            return $this->return_false(' '.($key + 1).'：==> 已经采集文章：'.$_title);
        }
        // 只采集今天的
        if($_ctime < $this->startTime){
            return $this->return_die(' '.($key + 1).'：==> 文章：不是今天的文章：'.$_title);
        }

        // 如果没有标题
        /*if(empty($_title)){
            return $this->return_false(' '.($key + 1).'：==> 文章：没有标题，不能采集：'.$_title);
        }*/
        // 只采集有评论的
        /*if($_item['comment'] < 1){
            return $this->return_false(' '.($key + 1).'：==> 文章：评论数过少，不采集：'.$_title);
        }*/

        // 全匹配 精准匹配
        if((strpos($_desc, $this->keyword) === false) && strpos($_title, $this->keyword) === false){
            return $this->return_false('==> 文章：文章没有精准匹配到搜索的关键字！');
        }
        // 排除关键字 宋正兴
        if(($this->keyword == '董事长宋正') && (strpos($_desc, '宋正兴') !== false) || strpos($_title, '宋正兴') !== false){
            return $this->return_false('==> 文章：文章匹配到其他关键词！');
        }

        // 判断 情感倾向
        //  "sentiment":2,   // 表示情感极性分类结果，0:负向，1:中性，2:正向
        /* $sentiment = '';  // 默认
        $full      = [0 => '负向', 1 => '中性', 2 => '正向'];
        $result    = (new BaiduNlp())->sentiment($_desc);
        if(isset($result['items'][0]['sentiment'])){
            $sentiment = $full[$result['items'][0]['sentiment']] ?? $sentiment;
        } */
        $sentiment = $this->baiduNlp($_desc);


        $_channel  = '';
        $from_site = '快讯';
        $site_id   = 14;
        $_row      = [
            'channel'      => 'dispatch',
            'sentiment'    => $sentiment,
            'link'         => $_href,
            'title'        => trim($_title),
            'description'  => $_desc,
            'text'         => $_desc,
            'time'         => $_ctime,
            'images'       => [],
            'cover'        => '',
            'author'       => '',
            'from_channel' => $_channel,
            'from_site'    => $from_site,
            'site_id'      => $site_id,
        ];

        //var_dump($_row);
        if($is_file){
            $res = $this->saveFile($_row);
        } else{
            $res = $this->saveArticle($_row);
        }

        return $res;
    }

    // 获取api接口的列表(测试)
    //   采集接口用curl需要 Cookie
    public function getApiList($keyword, $page = 1, $size = 10)
    {
        if(empty($keyword)){
            return $this->return_die('传递采集关键字！');
        }


        if($page == 1){
            $last_id = 1000000000;
        } else{
            $last_id = Cache::get('caitongnews_dispatch');
            if(empty($last_id)){
                $last_id = 1000000000;
            }
        }
        if($last_id < 1000000){
            return $this->return_false('    财通社快讯：没有采集内容：'.$keyword, 500);
        }

        try{
            // https://api.caitongnews.com/V1/Archive/query
            $url  = 'https://api.caitongnews.com/V1/Archive/query';
            $post = ['last_id' => $last_id, 'category' => 'dispatch', 'keyword' => $keyword,];
            $res  = $this->apiCurl()->post($post)->request($url);
            $json = json_decode($res, true);
        } catch(\Exception $e){
            return $this->return_false($e->getMessage());
        }

        if(empty($json['data'])){
            return $this->return_die('    财通社快讯：没有采集内容：'.$keyword);
        }

        // 缓存
        unset($json['data']['nums']);
        $ids = array_column($json['data'], 'id');
        Cache::set('caitongnews_dispatch', min($ids));

        return $json['data'];
    }


}

